//
//  GTGiftDetailViewController.m
//  GiftTalk
//
//  Created by Wan on 16/3/28.
//  Copyright © 2016年 Wan. All rights reserved.
//  礼物详情页

#import "GTGiftDetailViewController.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import <SVProgressHUD.h>
#import "GTSearchGift.h"
#import <MJExtension.h>
#import "GTGiftDetailHeaderView.h"
#import "GTSegment.h"
#import "GTUMSocialShare.h"
#import <SDWebImageDownloader.h>
#import <View+MASShorthandAdditions.h>
#import "GTBuyGiftController.h"
#import <MJRefresh.h>
#import "GTGiftComment.h"
#import "GTGiftCommentCell.h"
#import "GTPageScrollView.h"

@interface GTGiftDetailViewController () <UIScrollViewDelegate, UIWebViewDelegate, UITableViewDelegate, UITableViewDataSource>

/** 请求管理器 */
@property (strong, nonatomic) AFHTTPSessionManager *manager;
/** 礼物实体模型 */
@property (strong, nonatomic) GTSearchGift *giftItem;
/** 顶部容器高度 */
@property (assign, nonatomic) CGFloat containerHeight;
/** 评论模型数组 */
@property (strong, nonatomic) NSMutableArray *comments;
/** 记录下一次请求地址 */
@property (strong, nonatomic) NSString *nextPage;
/** 分享图片 */
@property (strong, nonatomic) UIImage *shareImage;

/** 详情页面 */
@property (weak, nonatomic) UIWebView *webView;
/** 评论详情页 */
@property (weak, nonatomic) UITableView *commentTableView;
/** 滚动视图 */
@property (weak, nonatomic) UIView *containerView;
/** 礼物详细页头部视图 */
@property (weak, nonatomic) GTGiftDetailHeaderView *detailHeader;
/** 礼物详细页 商品信息 & 评论 */
@property (weak, nonatomic) GTSegment *segment;
/** 评论按钮 */
@property (weak, nonatomic) UIButton *postCommentBtutton;
/** 底部工具条 */
@property (weak, nonatomic) UIView *bottomBarTool;
/** 评论文本框 */
@property (weak, nonatomic) UITextField *commentTextField;
@end

@implementation GTGiftDetailViewController

#pragma mark - 懒加载
- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (NSMutableArray *)comments
{
    if (!_comments) {
        _comments = [NSMutableArray array];
    }
    return _comments;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupNav];
    
    // 初始化分享按钮
    [self setupRightNavigationItem];
    
    // 初始化礼物页数据
    [self loadGiftItem];
    
}

/**
 *  初始化导航栏
 */
- (void)setupNav {
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor blackColor];
    self.navigationItem.title = @"礼物详情";
    // 隐藏导航栏
//    self.navigationController.navigationBar.hidden = YES;
}

#pragma mark - SNS Share
/**
 *  初始化分享按钮
 */
- (void)setupRightNavigationItem {
    // 设置分享按钮
//    UIBarButtonItem *rightItem = [UIBarButtonItem itemWithImage:@"content-details_share" highlightedImage:nil target:self action:@selector(presentShareController)];
    //    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"content-details_share"] style:UIBarButtonItemStyleDone target:self action:@selector(presentShareController)];
}

/**
 *  弹出分享页面
 */
- (void)presentShareController
{
    // 加载页面数据
//    [GTUMSocialShare share:self.shareImage shareDescription:self.giftItem.giftDescription shareUrl:self.giftItem.url];
    [GTUMSocialShare shareByPresentVc:self shareImage:self.shareImage shareDescription:self.giftItem.giftDescription shareUrl:self.giftItem.url];
    
}

/**
 *  获取分享图片
 */
- (void)setupSharImage {
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:self.giftItem.cover_image_url] options:SDWebImageDownloaderLowPriority progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
        self.shareImage = image;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 设置UI界面
- (void)loadGiftItem {
    NSString *urlStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/items/%@?", self.giftId];
    
    [SVProgressHUD showWithStatus:@"礼物加载中..."];
    
    
    [self.manager GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        
        self.giftItem = [GTSearchGift mj_objectWithKeyValues:responseObject[@"data"]];
        
        // 初始化网页容器
        [self setupWebView];
        [self setupContainerView];
        // 初始化头部视图
        [self setupDetailHeader];
        // 初始化礼物信息 & 评论
        [self setupSegment];
        // 获取评论数据
        [self setupCommentsTableView];
        // 绑定Segment的点击事件
        [self setupSegmentClick];
        // 设置喜欢&购买
        [self setupBottomBar];
        // 获取分享图片
        [self setupSharImage];
        // 评论按钮
        [self setupCommentButton];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:error.description];
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
}

- (void)setupWebView {
    UIWebView *webView = [[UIWebView alloc] initWithFrame:GTScreenBounds];
    webView.height = GTScreenH - 44;
    [self.view addSubview:webView];
    webView.backgroundColor = GTBackgroundColor;
    [webView loadHTMLString:self.giftItem.detail_html baseURL:nil];
    webView.scrollView.delegate = self;
    self.webView = webView;
}

- (void)setupContainerView {
    UIView *containerView = [[UIView alloc] init];
    [self.webView.scrollView addSubview:containerView];
    self.containerView = containerView;
}

- (void)setupDetailHeader {
    GTGiftDetailHeaderView *headerView = [GTGiftDetailHeaderView giftDetailHeader];
    headerView.giftItem = self.giftItem;
    [self.containerView addSubview: headerView];
    self.detailHeader = headerView;
    
    // 设置礼物详细页，头部轮播视图位置
    headerView.frame = CGRectMake(0, 0, GTScreenW, self.giftItem.detailHeaderHeight);
}

- (void)setupSegment {
    GTSegment *segment = [GTSegment segment];
//    segment.backgroundColor = [UIColor yellowColor];
    [self.containerView addSubview:segment];
    segment.frame = CGRectMake(0, self.giftItem.detailHeaderHeight, GTScreenW, 44);
    segment.giftItem = self.giftItem;
    self.segment = segment;
    CGFloat containerH = CGRectGetMaxY(self.segment.frame);
    self.webView.scrollView.contentInset = UIEdgeInsetsMake(containerH + 64, 0, 0, 0);
    self.containerView.frame = CGRectMake(0, -containerH, GTScreenW, containerH);
    self.containerHeight = containerH;
}

- (void)setupCommentsTableView {
    UITableView *tableView = [[UITableView alloc] initWithFrame:GTScreenBounds];
    [self.view addSubview:tableView];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = GTBackgroundColor;
    tableView.contentInset = UIEdgeInsetsMake(self.containerHeight + 64, 0, 0, 0);
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.estimatedRowHeight = 80;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [tableView.mj_footer beginRefreshing];
    self.commentTableView = tableView;
}

- (void)setupSegmentClick {
    [self.segment descriptionButtonAddTarget:self selector:@selector(descriptionButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self descriptionButtonClick];
    [self.segment commentButtonClickAddTarget:self selector:@selector(commentButtonClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setupBottomBar {
    UIView *bottomBar = [[UIView alloc] init];
    [self.view addSubview:bottomBar];
    bottomBar.backgroundColor = [UIColor whiteColor];
    bottomBar.layer.borderWidth = 1.0;
    bottomBar.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [bottomBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.equalTo(@44);
    }];
    self.bottomBarTool = bottomBar;
    
    NSInteger kVerticalMargin = 6;
    NSInteger kHorizontalMargin = 20;
    // 喜欢按钮
    UIButton *likeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [likeBtn setImage:[UIImage imageNamed:@"postitem_like"] forState:UIControlStateNormal];
    [likeBtn setImage:[UIImage imageNamed:@"postitem_liked"] forState:UIControlStateSelected];
    [likeBtn setTitle:@"喜欢" forState: UIControlStateNormal];
    likeBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    likeBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [likeBtn setTitleColor:GTThemeColor forState:UIControlStateNormal];
    [bottomBar addSubview:likeBtn];
    [likeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomBar.mas_left).offset(kHorizontalMargin);
        make.top.equalTo(bottomBar.mas_top).offset(kVerticalMargin);
        make.bottom.equalTo(bottomBar.mas_bottom).offset(-kVerticalMargin);
        make.width.equalTo(self.view).dividedBy(3.4);
    }];
    [likeBtn layoutIfNeeded];
    
    likeBtn.layer.cornerRadius = likeBtn.height * 0.5;
    likeBtn.layer.borderColor = GTThemeColor.CGColor;
    likeBtn.layer.borderWidth = 1.0;
    likeBtn.clipsToBounds = YES;
    [likeBtn addTarget:self action:@selector(like:) forControlEvents:UIControlEventTouchUpInside];
    
    // 去购买
    UIButton *buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [bottomBar addSubview:buyButton];
    [buyButton setTitle:@"立即前往购买" forState:UIControlStateNormal];
    buyButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [buyButton setBackgroundColor:GTThemeColor];
    
    [buyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomBar.mas_top).offset(kVerticalMargin);
        make.bottom.equalTo(bottomBar.mas_bottom).offset(-kVerticalMargin);
        make.right.equalTo(bottomBar.mas_right).offset(-kHorizontalMargin);
        make.width.equalTo(self.view).dividedBy(2);
    }];
    [buyButton layoutIfNeeded];
    
    buyButton.layer.cornerRadius = buyButton.height * 0.5;
    buyButton.layer.borderColor = GTThemeColor.CGColor;
    buyButton.layer.borderWidth = 1.0;
    buyButton.clipsToBounds = YES;
    [buyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buyButton addTarget:self action:@selector(goTmall) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setupCommentButton {
    // 评论文本框
    UITextField *commentTextField = [[UITextField alloc] init];
    commentTextField.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:commentTextField];
    [commentTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.equalTo(@44);
    }];
    self.commentTextField = commentTextField;
    self.commentTextField.hidden = YES;
    
    // 评论按钮
    UIButton *commentBtn = [[UIButton alloc] init];
    [commentBtn setImage:[UIImage imageNamed:@"postitem_comment"] forState:UIControlStateNormal];
    [self.view addSubview:commentBtn];
    commentBtn.hidden = YES;
    self.postCommentBtutton = commentBtn;
    
    [commentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@38.0);
        make.width.equalTo(@38.0);
        make.right.equalTo(self.view.mas_right).offset(-20.0);
        make.bottom.equalTo(self.view.mas_bottom).offset(-64.0);
    }];
    
    [commentBtn addTarget:self action:@selector(postComment) forControlEvents:UIControlEventTouchUpInside];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)keyboardWillChangeFrameNotification:(NSNotification *)notification {
    // 获取键盘基本信息（动画时长与键盘高度）
    NSDictionary *userInfo = [notification userInfo];
    CGRect rect = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    
    CGFloat keyboardHeight = CGRectGetHeight(rect);
    CGFloat keyboardDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 修改下边距约束
    [self.commentTextField mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-keyboardHeight);
    }];
    
    // 更新约束
    [UIView animateWithDuration:keyboardDuration animations:^{
        [self.view layoutIfNeeded];
    }];
}

/**
 *  评论
 */
- (void)postComment {
    self.bottomBarTool.hidden = YES;
    self.commentTextField.placeholder = @"我也说几句...";
    self.commentTextField.hidden = NO;
    [self.commentTextField becomeFirstResponder];
    
}

- (void)like:(UIButton *)button {
    button.selected = !button.selected;
    NSString *showTip = button.selected ? @"收藏成功！" : @"取消收藏";
    
    [SVProgressHUD showInfoWithStatus:showTip];
    
}

- (void)goTmall {
    NSString *taobaoUrl = [self.giftItem.purchase_url stringByReplacingOccurrencesOfString:@"http://" withString:@"taobao://"];
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:taobaoUrl]]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:taobaoUrl]];
    } else {
        GTBuyGiftController *buyVc = [[GTBuyGiftController alloc] init];
        buyVc.url = self.giftItem.purchase_url;
        [self.navigationController pushViewController:buyVc animated:YES];
    }
}

#pragma mark - < UIScrollViewDelegate >
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    self.commentTextField.hidden = YES;
    [self.view endEditing:YES];
    
    CGFloat offsetY = scrollView.contentOffset.y;
//    GTLog(@"%f",offsetY);
    
    if (offsetY > - 108) {
        [self.view addSubview:self.segment];
        self.segment.frame = CGRectMake(0, 64, GTScreenW, 44);
    } else if (offsetY < -self.containerHeight - 64) {
        CGFloat scale = offsetY / (-self.containerHeight - 64);
        self.detailHeader.pageScrollView.transform = CGAffineTransformMakeScale(scale, scale);
    } else {
        [self.containerView addSubview:self.segment];
        self.segment.frame = CGRectMake(0, self.giftItem.detailHeaderHeight, GTScreenW, 44);
    }
}

#pragma mark - 加载评论数据
- (void)loadMoreData {
    self.nextPage = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/items/%@/comments?limit=20&offset=0",self.giftId];
    
    [self.manager GET:self.nextPage parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *commentArr = [GTGiftComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"comments"]];
        [self.comments addObjectsFromArray:commentArr];
        
        self.nextPage = responseObject[@"data"][@"paging"][@"next_url"];
        [self.commentTableView reloadData];
        [self.commentTableView.mj_footer endRefreshing];

        if (self.comments.count >= self.giftItem.comments_count) {
            [self.commentTableView.mj_footer endRefreshingWithNoMoreData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        GTLog(@"%@",error);
        [self.commentTableView.mj_footer endRefreshing];
    }];
}

#pragma mark - < UITableViewDataSource >
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.comments.count;
}


#pragma mark - < UITableViewDelegate >
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GTGiftCommentCell *commentCell = [GTGiftCommentCell cellWithTableView:tableView];
    GTGiftComment *comment = self.comments[indexPath.row];
    commentCell.comment = comment;
    return commentCell;
}


#pragma mark - segment按钮点击
- (void)descriptionButtonClick {
    self.webView.hidden = NO;
    self.commentTableView.hidden = YES;
    [self.webView.scrollView addSubview:self.containerView];
    self.webView.scrollView.contentOffset = self.commentTableView.contentOffset;
    self.postCommentBtutton.hidden = YES;
    self.commentTextField.hidden = YES;
    self.bottomBarTool.hidden = NO;
    [self.view endEditing:YES];
}

- (void)commentButtonClick {
    self.webView.hidden = YES;
    self.commentTableView.hidden = NO;
    [self.commentTableView addSubview:self.containerView];
    self.commentTableView.contentOffset = self.webView.scrollView.contentOffset;
    self.postCommentBtutton.hidden = NO;
}

- (void)dealloc {
    [self.manager invalidateSessionCancelingTasks:YES];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
